﻿//-----------------------------------------------------------------------
// <copyright file="SplashWindow.xaml.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>26/01/2013</date>
//-----------------------------------------------------------------------
using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace ConsoleHoster.View
{
	/// <summary>
	/// Interaction logic for SplashWindow.xaml
	/// </summary>
	public partial class SplashWindow : Window
	{
		private static SplashWindow instance;

		internal SplashWindow()
		{
			InitializeComponent();
		}

		public static void StartSplash(string argStatus)
		{
			if (instance == null)
			{
				StartInstanceOnSeparateThread(argStatus);
			}
		}

		public static void UpdateProgress(string argStatus)
		{
			ValidateInstanceConstructed();

			instance.ucProgress.Status = argStatus;
		}

		private static void ValidateInstanceConstructed()
		{
			if (instance == null)
			{
				throw new ApplicationException("Splash screen has not been initialized yet");
			}
		}

		public static void EndSplash()
		{
			ValidateInstanceConstructed();

			instance.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Send);
		}

		private static void StartInstanceOnSeparateThread(string argStatus)
		{
			Thread tmpSplashScreenThread = new Thread(new ParameterizedThreadStart(OnStart));
			tmpSplashScreenThread.SetApartmentState(ApartmentState.STA);
			tmpSplashScreenThread.IsBackground = true;
			tmpSplashScreenThread.Start(argStatus);
		}

		private static void OnStart(object argStatus)
		{
			instance = new SplashWindow();
			instance.WindowStartupLocation = WindowStartupLocation.CenterScreen;
			instance.ucProgress.Status = argStatus as String;
			instance.Show();

			Dispatcher.Run();
		}
	}
}
